<script setup xmlns="">
import router from "@/router/index.js";
// 导入图标
import { User, HomeFilled , SwitchButton , Goods, Tickets} from "@element-plus/icons-vue";
import OrderIcon from '@/assets/icons/order.svg'

import request, { SERVER_BASE_URL } from "@/utils/request.js";
import {onMounted, ref, watch} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from '@/stores/user';


// Pinia用户状态
const userStore = useUserStore();

// 定义emit
const emit = defineEmits(['update']);

// 监听路由变化，动态设置高亮
const activeMenu = ref(router.currentRoute.value.path);

// 默认展开的菜单
const defaultOpeneds = ref(['2']); // 用户管理菜单的索引

// 优化退出登录功能
const logout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    try {
      // 调用后端退出登录接口
      await request.post('/logout', { userId: user.value.id });
    } catch (error) {
      console.error('退出登录接口调用失败:', error);
      // 即使接口调用失败，也继续执行前端登出逻辑
    }
    
    // 清除本地存储
    localStorage.removeItem('user');
    localStorage.removeItem('token');
    
    // 清除Pinia状态
    userStore.logout();
    
    ElMessage.success('退出登录成功');
    emit('update');
    router.push('/'); // 跳转到首页
  } catch (error) {
    // 用户取消退出操作
    console.log('用户取消退出');
  }
}

// 使用 const 声明响应式对象
const user = ref({})

const nickname = ref('')
const avatar = ref('')

const updateUser = () => {
  try {
    // 添加错误处理并设置默认值
    const storedUser = localStorage.getItem('user') || '{}'
    user.value = JSON.parse(storedUser) || {}
    
    // 从用户对象中提取所需信息
    nickname.value = user.value.nickname || user.value.username || ''
    if (user.value.avatar){
      avatar.value = user.value.avatar
    }
    
    // 同步到Pinia
    userStore.setUser(user.value);
  } catch (e) {
    console.error('解析用户信息失败:', e);
    user.value = {}
  }
}

onMounted(() => {
  updateUser() // 确保挂载时执行更新
})

//处理头像图片url，添加时间戳避免缓存
const getAvatarUrl = (url) => {
  if (!url) return '';

  // 确保有服务器地址前缀
  const serverBaseUrl = SERVER_BASE_URL;
  let fullUrl = url;

  if (url.startsWith('/uploads/')) {
    fullUrl = serverBaseUrl + url;
  }

  // 添加时间戳
  const timestamp = Date.now();
  const result = fullUrl.includes('?')
      ? `${fullUrl.split('?')[0]}?t=${timestamp}`
      : `${fullUrl}?t=${timestamp}`;

  console.log('Avatar URL:', result);
  return result;
}

watch(
  () => router.currentRoute.value.path,
  (newPath) => {
    activeMenu.value = newPath;
  }
);
</script>

<template>
  <div class="common-layout">
    <el-container style="max-height: 100vh">
      <el-header style="background: lightskyblue; height: 74.5px;">
        <el-link :underline="false" :href="'/'" style="color: white;float: left;width: auto;height: 100%">
          <h1 style="height: 100%">校园网上超市管理后台</h1>
        </el-link>
        <div style="float: right;margin-top: 10px;margin-left: 10px;width: fit-content;display: flex;align-items: center;">
          <el-avatar :size="50" :src="getAvatarUrl(user.avatar)" class="user-avatar" />
          <el-text style="color: white;margin-left: 10px;font-size: 16px">{{ nickname }}</el-text>
        </div>
      </el-header>

      <el-container style="max-height: calc(100vh - 74.5px)">

        <el-aside width="200px" style="border-right: #ddd 1px solid">
          <el-menu router :default-active="activeMenu" :default-openeds="defaultOpeneds" style="border: none">
            <el-menu-item index="/admin/home">
              <el-icon><HomeFilled/></el-icon>
              处理中心
            </el-menu-item>
            <el-sub-menu index="2" >
              <template #title>
                <el-icon><User /></el-icon>
                <span>用户管理</span>
              </template>
              <el-menu-item index="/admin/usermanagement">账户管理</el-menu-item>
              <el-menu-item index="/admin/loginlog">登录日志</el-menu-item>
            </el-sub-menu>
            <el-menu-item index="/admin/commoditymanagement">
              <el-icon><Goods /></el-icon>
              商品管理
            </el-menu-item>
            <el-menu-item index="/admin/ordermanagement">
              <el-icon><OrderIcon style="width: 1em; height: 1em;"/></el-icon>
              订单管理
            </el-menu-item>
            <el-menu-item index="/admin/articlemanagement">
              <el-icon><Tickets /></el-icon>
              文章管理
            </el-menu-item>
            <el-menu-item @click="logout">
              <el-icon><SwitchButton/></el-icon>
              退出登录
            </el-menu-item>
          </el-menu>
        </el-aside>

        <el-main style="min-height: calc(100vh - 74.5px);padding: 10px;padding-right: 20px" >
          <div>
              <router-view></router-view>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped>
/* 整体布局优化 */
.common-layout {
  background: #f0f2f5;
}

/* 头部样式升级 */
.el-header {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%) !important;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
  padding: 0 30px !important;
}

/* 侧边栏菜单优化 */
.el-aside {
  :deep(.el-menu) {
    .el-menu-item {
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      
      &:hover {
        transform: translateX(4px);
        box-shadow: 2px 0 8px rgba(64,158,255,0.2);
      }
      
      &.is-active {
        box-shadow: 2px 0 12px rgba(64,158,255,0.3);
      }
    }
  }
}

/* 主内容区域优化 */
.el-main {
  background: #f8fafc;
  
  :deep(.el-scrollbar__view) {
    min-height: 100%;
  }
}

/* 全局字体优化 */
:root:root {
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 
    'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-aside {
    width: 60px !important;
    
    :deep(.el-menu-item span) {
      display: none;
    }
  }
}

/* 侧边栏菜单优化 */
.el-aside {
  background: white !important;
  box-shadow: 2px 0 8px rgba(0,0,0,0.05);
  
  :deep(.el-menu) {
    border-right: none;
    
    .el-menu-item {
      height: 56px;
      line-height: 56px;
      margin: 8px 12px;
      border-radius: 8px;
      transition: all 0.3s;
      
      &:hover {
        background: rgba(64,158,255,0.1);
      }
      
      &.is-active {
        background: #409eff;
        color: white;
        font-weight: 500;
        
        .el-icon {
          color: white;
        }
      }
    }
  }
}

/* 主内容区域优化 */
.el-main {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  min-height: calc(100vh - 106px);
}
</style>